package matrix

func spiralOrder(matrix [][]int) []int {
	a := 0
	b := 0
	c := len(matrix)-1
	d := len(matrix[0]) - 1
	ans := make([]int, len(matrix)*len(matrix[0]))
	next := 0
	for a <= c && b <= d {
		next = spiralCollectAns(a, b, c, d, ans, matrix, next)
		a++
		b++
		c--
		d--
	}
	return ans
}

func spiralCollectAns(a, b, c, d int, ans []int, matrix [][]int, next int) int {
	if a == c {
		for i:=b; i<=d; i++ {
			ans[next] = matrix[a][i]
			next++
		}
		return next
	}
	if b == d {
		for i:=a; i<=c; i++ {
			ans[next] = matrix[i][b]
			next++
		}
		return next
	}
	for i:=a; i<d; i++ {
		ans[next] = matrix[a][i]
		next++
	}
	for i:=a; i<c; i++ {
		ans[next] = matrix[i][d]
		next++
	}
	for i:=d; i>b; i-- {
		ans[next] = matrix[c][i]
		next++
	}
	for i:=c; i>a; i-- {
		ans[next] = matrix[i][a]
		next++
	}
	return next
}
